/**
 * Copyright (c) 2011 ~ 2013 Deepin, Inc.
 *               2011 ~ 2013 jouyouyun
 *
 * Author:      jouyouyun <jouyouwen717@gmail.com>
 * Maintainer:  jouyouyun <jouyouwen717@gmail.com>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, see <http://www.gnu.org/licenses/>.
 **/

package main

import (
	"dlib"
	"dlib/dbus"
	"fmt"
	"time"
)

type TestTimer struct {
	IdleTimeOut func(int32)
}

var (
	cookieTimer map[int32]*time.Timer
	closeTimer  chan bool
	m           = &TestTimer{}

	genID = func() func() int32 {
		id := int32(0)
		return func() int32 {
			tmp := id
			id += 1
			return tmp
		}
	}()
)

func (m *TestTimer) GetDBusInfo() dbus.DBusInfo {
	return dbus.DBusInfo{
		"com.deepin.test.Timer",
		"/com/deepin/test/Timer",
		"com.deepin.test.Timer",
	}
}

func startTimer(timeout uint32, cookie int32) {
	defer func() {
		if err := recover(); err != nil {
			fmt.Println("recover err:", err)
		}
	}()

	timer := time.NewTimer(time.Second * time.Duration(timeout))
	cookieTimer[cookie] = timer
	select {
	case <-timer.C:
		fmt.Println("Timer Timeout. Cookie:", cookie)
		m.IdleTimeOut(cookie)
		timer.Stop()
		delete(cookieTimer, cookie)
	case <-closeTimer:
		fmt.Println("Close Timer. Cookie:", cookie)
	}
	fmt.Println("Start Timer End...")
}

func endTimer(cookie int32) {
	timer, ok := cookieTimer[cookie]
	if ok {
		timer.Stop()
		delete(cookieTimer, cookie)
		fmt.Println("End Timer. Cookie:", cookie)
		closeTimer <- true
	}
}

func main() {
	cookieTimer = make(map[int32]*time.Timer)
	closeTimer = make(chan bool)

	dbus.InstallOnSession(m)
	cookie := genID()
	go startTimer(5, cookie)
	time.Sleep(time.Second * 2)
	endTimer(cookie)

	dlib.StartLoop()
}
